/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.letmeshare.stockkeeper.stock.entities;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import org.letmeshare.stockkeeper.stock.exception.InsufficientStockException;
import org.letmeshare.stockkeeper.validator.ValidationException;
import org.letmeshare.stockkeeper.validator.Validator;

/**
 *
 * @author ibisuser1
 */
@Entity
public class Stock implements Serializable, Validator {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;
    @OneToOne
    private Item item;
    private double remainingQty;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    public double getRemainingQty() {
        return remainingQty;
    }

    public void setRemainingQty(double remainingQty) {
        this.remainingQty = remainingQty;
    }

    public double addStock(double qty) {
        if (qty < 0) {
            throw new IllegalArgumentException("Invalid quantity");
        }
        this.remainingQty += qty;
        return remainingQty;
    }
    
    public double consumeStock(double qty) {
        if (qty < 0) {
            throw new IllegalArgumentException("Invalid quantity");
        }
        if (qty > remainingQty) {
            throw new InsufficientStockException();
        }
        this.remainingQty -= qty;
        return remainingQty;
    }
    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Stock)) {
            return false;
        }
        Stock other = (Stock) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "org.letmeshare.stockkeeper.entities.stock.Stock[ id=" + id + " ]";
    }

    public void validate() throws ValidationException {
        if (item == null) {
            throw new IllegalArgumentException("Item required");
        }
        item.validate();
        if (remainingQty<0) {
            throw new IllegalArgumentException("Invalid remaining quantity");
        }
    }
    
}
